//
//  ViewController.m
//  dseman
//
//  Created by admin on 2/23/13.
//  Copyright (c) 2013 admin. All rights reserved.
//

#import "ViewController.h"
#import "MyCell.h"
#import "InformaticToolbar.h"
#import "ParserDelegate.h"


@interface ViewController ()

@property (nonatomic, strong) NSTimer *updateProgressTimer;

@end

@implementation ViewController

@synthesize updateProgressTimer = _updateProgressTimer;



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [item_names count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    MyCell *cell = (MyCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //если ячейка не найдена - создаем новую
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCell"owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    cell.indicator.image = [UIImage imageNamed:@"led_red_black.png"];
    
    cell.property_name.text = [item_names objectAtIndex:indexPath.row];
    cell.value1.text        = [item_values objectAtIndex:indexPath.row];
    cell.value2.text        = [item_values2 objectAtIndex:indexPath.row];
    
    return cell;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    titleview.title = @"Не подключено";
    [indicator stopAnimating];
    
    // Do any additional setup after loading the view, typically from a nib.
    item_names = [[NSMutableArray alloc] init];
    [item_names addObjectsFromArray:@[@"Status\n", @"Battery\n", @"GenVoltage\n", @"GenCurrent\n", @"MainsVoltage\n", @"MainsCurrent\n", @"MainsAvailable\n", @"GenAvailable\n", @"HoursRun\n"]];
    
 //   item_values = [[NSMutableArray alloc] init];
    
 //   for (int i = 0;i<=(item_names.count-1);i++) {
 //       [item_values addObject:@"??"];
 //        }

    [self addLabelBarItemSet:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)GetData:(int) obj_id
{
    current_id = obj_id;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.3.165/spidercgi.exe?getgenparams=%i",current_id]]
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
    
    // создаём соединение и начинаем загрузку
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    if (connection) {
        // соединение началось
        label.text = @"Connecting...";
        // создаем NSMutableData, чтобы сохранить полученные данные
        receivedData = [NSMutableData data];
    } else {
        // при попытке соединиться произошла ошибка
        label.text = @"Connection error!";
    }
}

- (IBAction)refresh:(id)sender {

    
    [indicator startAnimating];
    
    [self GetData:9];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // добавляем новые данные к receivedData
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // получен ответ от сервера
    [receivedData setLength:0];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // данные получены
    // здесь можно произвести операции с данными
    
    // можно узнать размер загруженных данных
    //NSString *dataString = [[NSString alloc] initWithFormat:@"Received %d bytes of data",[receivedData length]];
    
    //NSLog(dataString);
    
    ParserDelegate* delegate = [ParserDelegate new];
    NSXMLParser* parser = [[NSXMLParser alloc] initWithData:receivedData];
    
    [parser setDelegate:delegate];
    [parser parse];
    
    while ( ! delegate.done ) sleep(1);

    [tableview beginUpdates];
    
    titleview.title = [NSString stringWithFormat:@"Обновлено %@", [delegate.key_values objectForKey:@"DateTime\n"]];
    
    if (current_id == 9) {
        item_values = [[NSMutableArray alloc] init];}
    if (current_id == 10) {
        item_values2 = [[NSMutableArray alloc] init];}
   
    
    for (int i = 0;i<=(item_names.count-1);i++) {
       // NSLog(@"item name: %@",[item_names objectAtIndex:i]);
       // NSLog(@"delegate value: %@",[delegate.key_values objectForKey:[item_names objectAtIndex:i]]);
        
        if ([delegate.key_values objectForKey:[item_names objectAtIndex:i]]== nil) {
            [delegate.key_values setValue:@"??" forKey:[item_names objectAtIndex:i]];
        }
        
        if (current_id==9) {
            [item_values addObject:[delegate.key_values objectForKey:[item_names objectAtIndex:i]]];
        }
        if (current_id==10) {
            [item_values2 addObject:[delegate.key_values objectForKey:[item_names objectAtIndex:i]]];
        }
    }
    
    [tableview endUpdates];
    
    [tableview performSelector:@selector(reloadData) withObject:nil];
    
    if (current_id==9) [self GetData:10];
        else [indicator stopAnimating];
 
}

- (IBAction)addLabelBarItemSet:(id)sender
{
//    ITLabelBarItemSet *labelBarItemSet = [ITLabelBarItemSet labelBarItemSetWithDismissTarget:self andAction:@selector(dismissBarItemSet:)];
//    labelBarItemSet.textLabel.text = @"This is text label. ";
//    labelBarItemSet.detailTextLabel.text = @"This is detail text label. ";
//    [self pushBarItemSet:labelBarItemSet animated:YES];
}

- (void)dismissBarItemSet:(ITBarItemSet *)sender
{
    [self removeBarItemSet:sender animated:YES];
}


- (IBAction)btConnect:(id)sender {
  //  [self.view removeFromSuperview];
    View = self.view;
    self.view = View2;

}

- (IBAction)btMain:(id)sender {
    self.view = View;
    
}
@end
